import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class WeappVersionService extends BaseService<any> {
  private readonly logger = new Logger(WeappVersionService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * add
   * 对应 PHP: WeappVersionService_admin::add()
   * 逻辑类型: undefined - undefined
   */
  async add(data: any[]) {
    // 基于PHP真实逻辑: add
    // PHP原文: $uploading = $this->model->where([ ['site_id', '=', $this->site_id], ['status', '=', 0] ])->field('id')->findOrEmpty();         if (!$uploading->isEmp...
const uploading = this.model.where([ ['site_id', '=', this.site_id], ['status', '=', 0) )).field('id').findOrEmpty(];
        if (!uploading.isEmpty()) throw new BusinessException('WEAPP_UPLOADING'];

        const version_no = this.model.where([ ['site_id', '=', this.site_id) )).order('version_no desc').field('version_no').findOrEmpty().toArray().version_no || 0;
        version_no += 1;
        const version = "1.0.{version_no}";

        const upload_res = this.coreWeappCloudService.setConfig(function () {
            const config = this.coreWeappConfigService.getWeappConfig(this.site_id);
            return [
                app_id: config.app_id,
                upload_private_key: config.upload_private_key,
                addon: this.coreSiteService.getAddonKeysBySiteId(this.site_id)
            ];
  }

  /**
   * getPreviewImage
   * 对应 PHP: WeappVersionService_admin::getPreviewImage()
   * 逻辑类型: undefined - undefined
   */
  async getPreviewImage() {
    // 基于PHP真实逻辑: getPreviewImage
    // PHP原文: try {             $version = $this->model->where([ ['site_id', '=', $this->site_id] ])->order('id desc')->findOrEmpty();             if (!$version->is...
try {
            const version = this.model.where([ ['site_id', '=', this.site_id) )).order('id desc').findOrEmpty(];
            if (!version.isEmpty() || in_[version.status, [CloudDict.APPLET_UPLOAD_SUCCESS, CloudDict.APPLET_AUDITING))) {
                if (version.from_type == 'cloud_build') {
                    return this.coreWeappCloudService.getWeappPreviewImage(];
                } } } else {
                    return image_to_base64(this.coreWeappService.getWeappPreviewImage(this.site_id), true;
  }
  }

  /**
   * getPage
   * 对应 PHP: WeappVersionService_admin::getPage()
   * 逻辑类型: undefined - undefined
   */
  async getPage(where: any[]) {
    // 基于PHP真实逻辑: getPage
    // PHP原文: $field = 'id, version, version_no, desc, create_time, status, fail_reason, task_key';         $order = 'create_time desc';         $where[] = ['site_i...
const field = 'id, version, version_no, desc, create_time, status, fail_reason, task_key';
        const order = 'create_time desc';
        where[] = ['site_id', '=', this.site_id];
        const search_model = this.model.where(where).field(field).order(order).append(.status_name];
        return this.pageQuery(search_model);
    }

    /**
     * 编辑
     * @param int id
     * @param data
     * @return true
     */
    async edit(int id, data)
    {
        data.status = 0;
        data.update_time = time(];
        this.model.where([['id', '=', id], ['site_id', '=', this.site_id) )).create(data);
        return true;
    }

    /**
     * 删除
     * @param int id
     * @return true
     */
    async del(int id){
        this.model.where([['id', '=', id], ['site_id', '=', this.site_id))).delete(];
        return true;
    }

    /**
     * 获取小程序上传日志
     * @param string key
     * @return null
     */
    async getUploadLog(string key) {
        const build_log = this.coreWeappCloudService.getWeappCompileLog(key);

        if (typeof build_log.data) && typeof build_log.data[0)) && is_[build_log.data[0))) {
            const last = end(build_log.data[0)];
            if (last.code == 0) {
                this.weappVersionService.update([status: CloudDict.APPLET_UPLOAD_FAIL, fail_reason: last.msg || '', update_time: time() ], [task_key: key]];
                return build_log;
            }
            if (last.percent == 100) {
                this.weappVersionService.update([status: CloudDict.APPLET_UPLOAD_SUCCESS, update_time: time() ], [task_key: key]];
            }
  }

  /**
   * edit
   * 对应 PHP: WeappVersionService_admin::edit()
   * 逻辑类型: undefined - undefined
   */
  async edit(id: any[], data: any[]) {
    // 基于PHP真实逻辑: edit
    // PHP原文: $data['status'] = 0;         $data['update_time'] = time();         $this->model->where([['id', '=', $id], ['site_id', '=', $this->site_id] ])->create...
data.status = 0;
        data.update_time = time(];
        this.model.where([['id', '=', id], ['site_id', '=', this.site_id) )).create(data);
        return true;
    }

    /**
     * 删除
     * @param int id
     * @return true
     */
    async del(int id){
        this.model.where([['id', '=', id], ['site_id', '=', this.site_id))).delete(];
        return true;
    }

    /**
     * 获取小程序上传日志
     * @param string key
     * @return null
     */
    async getUploadLog(string key) {
        const build_log = this.coreWeappCloudService.getWeappCompileLog(key);

        if (typeof build_log.data) && typeof build_log.data[0)) && is_[build_log.data[0))) {
            const last = end(build_log.data[0)];
            if (last.code == 0) {
                this.weappVersionService.update([status: CloudDict.APPLET_UPLOAD_FAIL, fail_reason: last.msg || '', update_time: time() ], [task_key: key]];
                return build_log;
            }
            if (last.percent == 100) {
                this.weappVersionService.update([status: CloudDict.APPLET_UPLOAD_SUCCESS, update_time: time() ], [task_key: key]];
            }
  }

  /**
   * del
   * 对应 PHP: WeappVersionService_admin::del()
   * 逻辑类型: undefined - undefined
   */
  async del(id: number) {
    // 基于PHP真实逻辑: del
    // PHP原文: $this->model->where([['id', '=', $id], ['site_id', '=', $this->site_id]])->delete();         return true;     }      /**      * 获取小程序上传日志      * @para...
this.model.where([['id', '=', id], ['site_id', '=', this.site_id))).delete(];
        return true;
    }

    /**
     * 获取小程序上传日志
     * @param string key
     * @return null
     */
    async getUploadLog(string key) {
        const build_log = this.coreWeappCloudService.getWeappCompileLog(key);

        if (typeof build_log.data) && typeof build_log.data[0)) && is_[build_log.data[0))) {
            const last = end(build_log.data[0)];
            if (last.code == 0) {
                this.weappVersionService.update([status: CloudDict.APPLET_UPLOAD_FAIL, fail_reason: last.msg || '', update_time: time() ], [task_key: key]];
                return build_log;
            }
            if (last.percent == 100) {
                this.weappVersionService.update([status: CloudDict.APPLET_UPLOAD_SUCCESS, update_time: time() ], [task_key: key]];
            }
  }

  /**
   * getUploadLog
   * 对应 PHP: WeappVersionService_admin::getUploadLog()
   * 逻辑类型: undefined - undefined
   */
  async getUploadLog(key: string) {
    // 基于PHP真实逻辑: getUploadLog
    // PHP原文: $build_log = (new CoreWeappCloudService())->getWeappCompileLog($key);          if (isset($build_log['data']) && isset($build_log['data'][0]) && is_arr...
const build_log = this.coreWeappCloudService.getWeappCompileLog(key);

        if (typeof build_log.data) && typeof build_log.data[0)) && is_[build_log.data[0))) {
            const last = end(build_log.data[0)];
            if (last.code == 0) {
                this.weappVersionService.update([status: CloudDict.APPLET_UPLOAD_FAIL, fail_reason: last.msg || '', update_time: time() ], [task_key: key]];
                return build_log;
            }
            if (last.percent == 100) {
                this.weappVersionService.update([status: CloudDict.APPLET_UPLOAD_SUCCESS, update_time: time() ], [task_key: key]];
            }
  }
}
